﻿using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.IO;
using System.Windows.Documents;
using System.Windows;
using System.Xml.Serialization;
using System.Windows.Controls;

namespace GIALib
{
    [Serializable]
    public class Resume : INotifyPropertyChanged
    {
        #region Fields and Constants

        //The constants specific to this class
        public static class Const
        { 
            //name of the folder
            public const string ResumesFolderName = "Resumes";
        }

        private string relativePath;
        
        #endregion

        #region Properties

        /// <summary>
        /// The relative path for the resume files
        /// </summary>
        public string RelativePath
        {
            get { return relativePath; }
            set
            {
                if (relativePath != value)
                {
                    relativePath = value;
                    OnPropertyChanged("relativePath");
                }
            }
        }

        /// <summary>
        /// The absolute path for the resume files
        /// </summary>
        [XmlIgnore]
        public string AbsolutePath
        {
            get
            { 
                //absolute path to the application folder
                string appLocation = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                    App.ApplicationFolderName);
                if (appLocation != null)
                {
                    return Path.Combine(appLocation, relativePath);
                }
                else
                {
                    return string.Empty;
                }
            }
        }

        #endregion

        #region Constructors

        public Resume()
        { }

        #endregion

        #region Methods

        /// <summary>
        /// save the resume to disk
        /// </summary>
        /// <param name="resumeText"></param>
        /// <param name="resumeFileName"></param>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "GIALib.Resume.Save(System.String,System.String):System.Void")]
        public void Save(TextRange resumeText, string resumeFileName)
        { 
            //data format for the resume file.
            string dataFormat = DataFormats.Rtf;

            //absolute path to the application folder
            string appLocation = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                App.ApplicationFolderName);

            //absolute path to the resumes folder
            string resumesLocation = Path.Combine(appLocation, Const.ResumesFolderName);
            
            //fully qualified path to the new resume file
            resumeFileName = GetSafeFileName(resumeFileName);
            string resumeAbsoluePath = Path.Combine(resumesLocation, resumeFileName);

            try
            {
                //create the storied directory if it does't exists
                if (!Directory.Exists(resumesLocation))
                {
                    Directory.CreateDirectory(resumesLocation);
                }

                //open the file to write the richtext
                using (FileStream fs = File.Create(resumeAbsoluePath))
                {
                    //strore the relative path for the resume
                    this.relativePath = Path.Combine(Const.ResumesFolderName, resumeFileName);

                    //save the resume to disk
                    if (resumeText.CanSave(dataFormat))
                    {
                        resumeText.Save(fs, dataFormat);
                    }
                }
            }
            catch
            {
                // Could not save the story. Handle all exceptions
                // the same, ignore and continue.
            }
        }

        /// <summary>
        /// load the resume from file to TextRange
        /// </summary>
        /// <param name="resumeText"></param>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        public void Load(TextRange resumeText)
        { 
            //data format for the person's resume file
            string dataFormat = DataFormats.Rtf;

            if (File.Exists(this.AbsolutePath))
            {
                try
                {
                    //open the file to read
                    using (FileStream fs = File.OpenRead(this.AbsolutePath))
                    {
                        if (resumeText.CanLoad(dataFormat))
                        {
                            resumeText.Load(fs, dataFormat);
                        }
                    }
                }
                catch
                {
                    // Could not load the story. Handle all exceptions
                    // the same, ignore and continue.
                }
            }
        }

        /// <summary>
        /// Save the person's resume on the file system.  Accepts plain text for Gedcom support
        /// </summary>
        /// <param name="resumeText"></param>
        /// <param name="resumeFileName"></param>
          [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "GIALib.Resume.Save(System.String,System.String):System.Void")]
           public void Save(string resumeText, string resumeFileName)
            {
                //data format for the resume file
                string dataFormat = DataFormats.Rtf;

                //absolute path to the application folder
                string appLocation = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                    App.ApplicationFolderName);

                //absolute path for the resume file
                string resumesLocation = Path.Combine(appLocation, Const.ResumesFolderName);

                //fully qualified path to the new resume file
                resumeFileName = GetSafeFileName(resumeFileName);
                string resumeAbsolutePath = Path.Combine(resumesLocation, resumeFileName);

                //convert the text into a TextRange.This will allow saving the resume to disk as RTF.
                TextBlock block = new System.Windows.Controls.TextBlock();
                block.Text = resumeText;
                TextRange range = new TextRange(block.ContentStart, block.ContentEnd);

                try
                {
                    //create the resumes directory if it does't exist
                    if(!Directory.Exists(resumesLocation))
                    {
                        Directory.CreateDirectory(resumesLocation);
                    }

                    //open the file to write the richtext
                    using (FileStream fs = File.Create(resumeAbsolutePath))
                    {
                        //store the relative path to the resume
                        this.relativePath = Path.Combine(Const.ResumesFolderName, resumeFileName);

                        //save the resume
                        if(range.CanSave(dataFormat))
                        {
                            range.Save(fs, dataFormat);
                        }
                    }
                }
                catch
                {
                   // Could not save the story. Handle all exceptions
                // the same, ignore and continue. 
                }
            }

        /// <summary>
        /// delete the person's resume if it exists
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        public void Delete()
        {
            //delete the person's resume if it exists
            if(File.Exists(this.AbsolutePath))
            {
                try
                {
                    File.Delete(this.AbsolutePath);
                }
                catch
                {
                    // Could not delete the file. Handle all exceptions
                    // the same, ignore and continue.
                }
            }
        }

        /// <summary>
        /// Return a string that is a safe file name.
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private static string GetSafeFileName(string fileName)
        {
            //list of invalid characters.
            char[] invalid = Path.GetInvalidFileNameChars();

            //remove all invalid characters.
            int pos;
            while((pos = fileName.IndexOfAny(invalid)) != -1)
            {
                fileName = fileName.Remove(pos, 1);
            }

            return fileName;
        }

        #endregion

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        #endregion

    }
}
